package com.jastar.android.game.gobang;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class AIPlayer {
    private static final int EMPTY = 0;
    private static final int HUMAN = 1;
    private static final int AI = 2;
    private final Random random = new Random();
    private boolean isMaster = false;

    public void setMaster(boolean master) {
        isMaster = master;
    }

    public interface BoardState {
        int[][] getBoard();

        boolean isValidMove(int row, int col);
    }

    public int[] makeMove(BoardState boardState) {
        int[][] board = boardState.getBoard();
        List<int[]> candidates = new ArrayList<>();

        // 第一步：寻找最佳候选位置
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == EMPTY) {
                    int score = evaluatePosition(board, i, j);
                    if (score > 0) candidates.add(new int[]{i, j, score});
                }
            }
        }

        // 第二步：选择最佳候选位置
        if (!candidates.isEmpty()) {
            candidates.sort((a, b) -> b[2] - a[2]); // 按评分降序排序
            int maxScore = candidates.get(0)[2];
            List<int[]> bestMoves = new ArrayList<>();
            for (int[] c : candidates) {
                if (c[2] == maxScore) bestMoves.add(c);
            }
            return bestMoves.get(random.nextInt(bestMoves.size()));
        }

        // 第三步：没有合适位置时随机落子
        return randomMove(boardState);
    }

    private int evaluatePosition(int[][] board, int row, int col) {
        int score = 0;

        // 简单评估规则（可扩展）
        score += evaluateDirection(board, row, col, 0, 1, 4);  // 水平
        score += evaluateDirection(board, row, col, 1, 0, 4);  // 垂直
        score += evaluateDirection(board, row, col, 1, 1, 4);  // 主对角线
        score += evaluateDirection(board, row, col, 1, -1, 4); // 副对角线
        if (isMaster) {
            score += evaluateDirection(board, row, col, 0, 1, 3);  // 水平
            score += evaluateDirection(board, row, col, 1, 0, 3);  // 垂直
            score += evaluateDirection(board, row, col, 1, 1, 3);  // 主对角线
            score += evaluateDirection(board, row, col, 1, -1, 3); // 副对角线
        }

        return score;
    }

    private int evaluateDirection(int[][] board, int row, int col, int dx, int dy, int step) {
        int aiCount = 0;
        int humanCount = 0;

        // 双向检测
        for (int i = -step; i <= step; i++) {
            int r = row + i * dx;
            int c = col + i * dy;

            if (r < 0 || r >= board.length || c < 0 || c >= board[0].length) continue;

            if (board[r][c] == AI) {
                aiCount++;
                if (isMaster) humanCount = 0;
            }
            if (board[r][c] == HUMAN) {
                humanCount++;
                if (isMaster) aiCount = 0;
            }
        }

        // 评分规则（优先防守和进攻）
        if (humanCount >= 4) return 1000;  // 阻止玩家五连
        if (aiCount >= 4) return 900;      // 自己即将五连
        if (humanCount == 3) return 200;   // 阻止玩家四连
        if (aiCount == 3) return 150;      // 自己形成四连
        return aiCount;                    // 其他情况
    }

    private int[] randomMove(BoardState boardState) {
        List<int[]> emptyCells = new ArrayList<>();
        int[][] board = boardState.getBoard();

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (boardState.isValidMove(i, j)) {
                    emptyCells.add(new int[]{i, j});
                }
            }
        }
        return emptyCells.isEmpty() ? new int[]{-1, -1} : emptyCells.get(random.nextInt(emptyCells.size()));
    }

}